package co.yixiang.modules.pay.zhifubao;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

public class AppControllerUtil {



    /**
     * 客户端返回对象的JSON字符串,去除循环包含
     *
     * @param response
     * @param object
     * @return
     */
    protected void resultAjaxDataApp(HttpServletResponse response, Object object, String dateFormat) throws IOException {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        //设置返回数据时间格式
        if(EmptyUtils.isEmpty(dateFormat)){
            jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor());
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor());
            jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
            jsonConfig.registerJsonValueProcessor(BigDecimal.class, new DateJsonValueProcessor());
            jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        }else{
            jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new DateJsonValueProcessor(dateFormat));
            jsonConfig.registerJsonValueProcessor(Timestamp.class, new DateJsonValueProcessor(dateFormat));
            jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(dateFormat));
            jsonConfig.registerJsonValueProcessor(BigDecimal.class, new DateJsonValueProcessor(dateFormat));
            jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        }
        JSONObject json =JSONObject.fromObject(object, jsonConfig);
        String result = json.toString();
        if (!response.isCommitted()) {
            response.reset();
        }
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(result);

    }

}
